import {
  getMaterials,
  getMaterialDetail,
  getMaterialCategories,
  applyMaterial,
  toggleFavoriteMaterial,
  getFavoriteMaterials
} from '@/api/material'
import { Toast } from 'vant'
import request from '@/utils/request'
import axios from 'axios'

// 物资状态模块
const state = {
  // 物资列表
  materials: {
    list: [],
    total: 0,
    loading: false
  },
  // 物资分类
  categories: {
    list: [],
    loading: false
  },
  // 当前详情
  currentMaterial: {
    data: null,
    loading: false
  },
  // 收藏物资
  favorites: {
    list: [],
    total: 0,
    loading: false
  },
  // 物资列表
  materialList: [],
  // 分页信息
  pagination: {
    current: 1,
    pageSize: 10,
    total: 0
  },
  // 统计数据
  statistics: {
    totalMaterials: 0,
    inStockItems: 0,
    lowStockItems: 0,
    pendingApprovals: 0,
    approvedApprovals: 0,
    rejectedApprovals: 0
  },
  // 预警设置
  warningSettings: {
    defaultWarningThreshold: 20,  // 默认预警阈值
    criticalThreshold: 10,        // 严重不足阈值
    warningThreshold: 30          // 即将预警阈值
  }
}

const mutations = {
  // 设置物资列表加载状态
  SET_MATERIALS_LOADING(state, loading) {
    state.materials.loading = loading
  },
  // 设置物资列表数据
  SET_MATERIALS_LIST(state, { list, total }) {
    state.materials.list = list
    state.materials.total = total
  },
  // 设置物资分类加载状态
  SET_CATEGORIES_LOADING(state, loading) {
    state.categories.loading = loading
  },
  // 设置物资分类数据
  SET_CATEGORIES_LIST(state, list) {
    state.categories.list = list
  },
  // 设置当前物资详情加载状态
  SET_CURRENT_MATERIAL_LOADING(state, loading) {
    state.currentMaterial.loading = loading
  },
  // 设置当前物资详情数据
  SET_CURRENT_MATERIAL(state, data) {
    state.currentMaterial.data = data
  },
  // 更新物资收藏状态
  UPDATE_MATERIAL_FAVORITE(state, { id, isFavorite }) {
    // 更新列表中的物资收藏状态
    if (state.materials.list.length > 0) {
      const material = state.materials.list.find(item => item.id === id)
      if (material) {
        material.isFavorite = isFavorite
      }
    }
    
    // 更新当前查看的物资收藏状态
    if (state.currentMaterial.data && state.currentMaterial.data.id === id) {
      state.currentMaterial.data.isFavorite = isFavorite
    }
    
    // 如果取消收藏，从收藏列表中移除
    if (!isFavorite && state.favorites.list.length > 0) {
      state.favorites.list = state.favorites.list.filter(item => item.id !== id)
      state.favorites.total = Math.max(0, state.favorites.total - 1)
    }
  },
  // 设置收藏物资加载状态
  SET_FAVORITES_LOADING(state, loading) {
    state.favorites.loading = loading
  },
  // 设置收藏物资列表数据
  SET_FAVORITES_LIST(state, { list, total }) {
    state.favorites.list = list
    state.favorites.total = total
  },
  SET_MATERIAL_LIST(state, list) {
    state.materialList = list
  },
  SET_PAGINATION(state, pagination) {
    state.pagination = pagination
  },
  SET_STATISTICS(state, statistics) {
    state.statistics = statistics
  },
  UPDATE_MATERIAL(state, material) {
    const index = state.materialList.findIndex(item => item.id === material.id)
    if (index !== -1) {
      state.materialList.splice(index, 1, material)
    }
  },
  SET_WARNING_SETTINGS(state, settings) {
    state.warningSettings = { ...state.warningSettings, ...settings }
  }
}

const actions = {
  // 获取物资列表
  async fetchMaterials({ commit }, params = {}) {
    commit('SET_MATERIALS_LOADING', true)
    try {
      const { data } = await getMaterials(params)
      commit('SET_MATERIALS_LIST', {
        list: data.items,
        total: data.total
      })
      return data
    } catch (error) {
      console.error('获取物资列表失败:', error)
      throw error
    } finally {
      commit('SET_MATERIALS_LOADING', false)
    }
  },
  
  // 获取物资分类
  async fetchCategories({ commit, state }) {
    // 如果已有分类数据且不是强制刷新，直接返回
    if (state.categories.list.length > 0) {
      return state.categories.list
    }
    
    commit('SET_CATEGORIES_LOADING', true)
    try {
      const { data } = await getMaterialCategories()
      commit('SET_CATEGORIES_LIST', data)
      return data
    } catch (error) {
      console.error('获取物资分类失败:', error)
      throw error
    } finally {
      commit('SET_CATEGORIES_LOADING', false)
    }
  },
  
  // 获取物资详情
  async fetchMaterialDetail({ commit }, id) {
    commit('SET_CURRENT_MATERIAL_LOADING', true)
    try {
      const { data } = await getMaterialDetail(id)
      commit('SET_CURRENT_MATERIAL', data)
      return data
    } catch (error) {
      console.error('获取物资详情失败:', error)
      throw error
    } finally {
      commit('SET_CURRENT_MATERIAL_LOADING', false)
    }
  },
  
  // 收藏/取消收藏物资
  async toggleFavorite({ commit }, { id, isFavorite }) {
    try {
      await toggleFavoriteMaterial(id, isFavorite)
      commit('UPDATE_MATERIAL_FAVORITE', { id, isFavorite })
      return true
    } catch (error) {
      console.error('更新收藏状态失败:', error)
      throw error
    }
  },
  
  // 申请物资
  async applyMaterial(_, data) {
    try {
      const res = await applyMaterial(data)
      return res.data
    } catch (error) {
      console.error('申请物资失败:', error)
      throw error
    }
  },
  
  // 获取收藏物资列表
  async fetchFavorites({ commit }, params = {}) {
    commit('SET_FAVORITES_LOADING', true)
    try {
      const { data } = await getFavoriteMaterials(params)
      commit('SET_FAVORITES_LIST', {
        list: data.items,
        total: data.total
      })
      return data
    } catch (error) {
      console.error('获取收藏物资列表失败:', error)
      throw error
    } finally {
      commit('SET_FAVORITES_LOADING', false)
    }
  },

  // 获取物资列表
  async getInventoryList({ commit }, params) {
    try {
      const response = await request({
        url: '/api/material/list',
        method: 'get',
        params
      })
      
      if (response.code === 200) {
        commit('SET_MATERIAL_LIST', response.data.list)
        commit('SET_PAGINATION', {
          current: params.page,
          pageSize: params.pageSize,
          total: response.data.total
        })
        return response
      } else {
        Toast.fail(response.message || '获取物资列表失败')
        return null
      }
    } catch (error) {
      console.error('获取物资列表失败:', error)
      Toast.fail('网络错误，请稍后重试')
      return null
    }
  },

  // 获取物资统计数据
  async getMaterialStatistics({ commit }) {
    try {
      const response = await request({
        url: '/api/material/statistics',
        method: 'get'
      })
      
      if (response.code === 200) {
        commit('SET_STATISTICS', response.data)
        return response.data
      } else {
        Toast.fail(response.message || '获取统计数据失败')
        return null
      }
    } catch (error) {
      console.error('获取统计数据失败:', error)
      Toast.fail('网络错误，请稍后重试')
      return null
    }
  },

  // 提交物资申请
  async submitMaterialApplication({ commit }, data) {
    try {
      const response = await request({
        url: '/api/material/apply',
        method: 'post',
        data
      })
      
      if (response.code === 200) {
        Toast.success('申请提交成功')
        return response.data
      } else {
        Toast.fail(response.message || '申请提交失败')
        return null
      }
    } catch (error) {
      console.error('申请提交失败:', error)
      Toast.fail('网络错误，请稍后重试')
      return null
    }
  },

  // 获取物资详情
  async getMaterialDetail({ commit }, id) {
    try {
      const response = await request({
        url: `/api/material/detail/${id}`,
        method: 'get'
      })
      
      if (response.code === 200) {
        commit('UPDATE_MATERIAL', response.data)
        return response.data
      } else {
        Toast.fail(response.message || '获取物资详情失败')
        return null
      }
    } catch (error) {
      console.error('获取物资详情失败:', error)
      Toast.fail('网络错误，请稍后重试')
      return null
    }
  },

  // 提交入库
  async submitInbound({ commit }, data) {
    try {
      const response = await request({
        url: '/api/material/inbound',
        method: 'post',
        data
      })
      
      if (response.code === 200) {
        // 更新物资库存
        commit('UPDATE_MATERIAL', {
          id: data.materialId,
          stock: response.data.newStock
        })
        return response.data
      } else {
        Toast.fail(response.message || '入库失败')
        return null
      }
    } catch (error) {
      console.error('入库失败:', error)
      Toast.fail('网络错误，请稍后重试')
      return null
    }
  },

  // 提交出库
  async submitOutbound({ commit }, data) {
    try {
      const response = await request({
        url: '/api/material/outbound',
        method: 'post',
        data
      })
      
      if (response.code === 200) {
        // 更新物资库存
        commit('UPDATE_MATERIAL', {
          id: data.materialId,
          stock: response.data.newStock
        })
        return response.data
      } else {
        Toast.fail(response.message || '出库失败')
        return null
      }
    } catch (error) {
      console.error('出库失败:', error)
      Toast.fail('网络错误，请稍后重试')
      return null
    }
  },

  // 获取物资列表（用于选择物资）
  async getMaterialList({ commit }, params = { page: 1, pageSize: 1000 }) {
    try {
      const response = await request({
        url: '/api/material/list',
        method: 'get',
        params
      })
      
      if (response.code === 200) {
        return response
      } else {
        Toast.fail(response.message || '获取物资列表失败')
        return null
      }
    } catch (error) {
      console.error('获取物资列表失败:', error)
      Toast.fail('网络错误，请稍后重试')
      return null
    }
  },

  // 获取预警列表
  async getWarningList({ commit }, params) {
    try {
      const response = await request({
        url: '/api/material/warning/list',
        method: 'get',
        params
      })
      
      if (response.code === 200) {
        return response
      } else {
        Toast.fail(response.message || '获取预警列表失败')
        return null
      }
    } catch (error) {
      console.error('获取预警列表失败:', error)
      Toast.fail('网络错误，请稍后重试')
      return null
    }
  },

  // 更新预警设置
  async updateWarningSettings({ commit }, data) {
    try {
      const response = await request({
        url: '/api/material/warning/settings',
        method: 'put',
        data
      })
      
      if (response.code === 200) {
        commit('SET_WARNING_SETTINGS', data)
        Toast.success('预警设置更新成功')
        return true
      } else {
        Toast.fail(response.message || '更新预警设置失败')
        return false
      }
    } catch (error) {
      console.error('更新预警设置失败:', error)
      Toast.fail('网络错误，请稍后重试')
      return false
    }
  },

  // 获取报表数据
  async getReportData({ commit }, { startDate, endDate }) {
    try {
      const response = await request({
        url: '/api/material/report',
        method: 'get',
        params: {
          startDate,
          endDate
        }
      })
      
      if (response.code === 200) {
        return response.data
      } else {
        Toast.fail(response.message || '获取报表数据失败')
        return null
      }
    } catch (error) {
      console.error('获取报表数据失败:', error)
      Toast.fail('获取报表数据失败')
      return null
    }
  }
}

const getters = {
  // 物资列表
  materialsList: state => state.materials.list,
  // 物资总数
  materialsTotal: state => state.materials.total,
  // 物资列表加载状态
  materialsLoading: state => state.materials.loading,
  // 物资分类列表
  categoriesList: state => state.categories.list,
  // 物资分类加载状态
  categoriesLoading: state => state.categories.loading,
  // 当前物资详情
  currentMaterial: state => state.currentMaterial.data,
  // 当前物资详情加载状态
  currentMaterialLoading: state => state.currentMaterial.loading,
  // 收藏物资列表
  favoritesList: state => state.favorites.list,
  // 收藏物资总数
  favoritesTotal: state => state.favorites.total,
  // 收藏物资加载状态
  favoritesLoading: state => state.favorites.loading,
  // 按分类ID获取分类名称
  getCategoryNameById: state => id => {
    const category = state.categories.list.find(item => item.id === id)
    return category ? category.name : ''
  },
  // 获取物资分类列表
  categoryList: state => state.categories.list,
  
  // 获取统计数据
  statistics: state => state.statistics,
  
  // 获取分页信息
  pagination: state => state.pagination,
  
  // 获取物资列表
  materialList: state => state.materialList,
  
  // 按分类获取物资
  getMaterialsByCategory: state => category => {
    return state.materialList.filter(item => item.category === category)
  },
  
 // 获取库存预警物资
  lowStockMaterials: state => {
    return state.materialList.filter(item => item.stock <= item.warningStock)
  },
  
  // 获取预警设置
  warningSettings: state => state.warningSettings,
  
  // 判断物资是否处于预警状态
  isWarningMaterial: state => material => {
    if (!material) return false
    const { defaultWarningThreshold, criticalThreshold, warningThreshold } = state.warningSettings
    const threshold = material.warningStock || defaultWarningThreshold
    
    if (material.stock <= criticalThreshold) {
      return { status: 'critical', level: '严重不足' }
    } else if (material.stock <= threshold) {
      return { status: 'low', level: '库存不足' }
    } else if (material.stock <= warningThreshold) {
      return { status: 'warning', level: '即将预警' }
    }
    return false
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 